package com.atguigu.gulimall.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.util.Jsons;
import com.atguigu.gulimall.pay.config.properties.AlipayProperties;
import com.atguigu.gulimall.util.consts.MqConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author nicc
 * @version 1.0
 * @className OrderPayedController
 * @date 2022-10-25 16:09
 *
 * 支付宝支付成功发送的异步请求
 */

@Slf4j
@RequestMapping("/api/payment/alipay")
@RestController
public class OrderPayedController {

    @Autowired
    AlipayProperties alipayProperties;


    @Autowired
    RabbitTemplate rabbitTemplate;


    /**
     * 支付宝支付成功就会远程调用这个方法，传来刚才支付的所有数据
     * @param params
     * @return
     */
    @PostMapping("/payed/success")
    public String listenpayed(@RequestParam Map<String, String> params) throws AlipayApiException {

        log.info("支付宝通知支付成功消息抵达...携带参数: {}", Jsons.toStr(params));

        boolean signVerified = AlipaySignature
                .rsaCheckV1(params,
                        alipayProperties.getAlipayPublicKey(),
                        alipayProperties.getCharset(),
                        alipayProperties.getSignType()); //调用SDK验证签名
        if (signVerified) {
            //1）、远程调用   2)、消息机制
            log.info("验签通过，准备通知订单服务修改订单状态为已支付");
            rabbitTemplate.convertAndSend(MqConst.ORDER_EVENT_EXCHANGE,
                    MqConst.RK_ORDER_PAYED,
                    Jsons.toStr(params));
            return "success";
        }

        log.error("验签失败，此请求为伪造请求");

        return "error";
    }

}
